package cn.itcast.n4.exercise;

import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * className: ExerciseTransfer
 * description:
 * date: 2023/2/13 0013-PM 8:15:10
 * <p>
 * project: concurrent
 * package: cn.itcast.n4.exercise
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
@Slf4j(topic = "c.ExerciseTransfer")
public class ExerciseTransfer {

    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(1000);
        Account b = new Account(1000);
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transfer(b, randomAmount());
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transfer(a, randomAmount());
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        // 查看转账 2000 次后的总额
        log.debug("total:{}", (a.getMoney() + b.getMoney()));
    }

    /**
     * Random 为线程安全
     */
    static Random random = new Random();

    /**
     * 随机 1~100
     *
     * @return {@link Integer} 随机数
     */
    public static int randomAmount() {
        return random.nextInt(100) + 1;
    }
}

class Account {
    private int money;

    public Account(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    /**
     * 转账
     *
     * @param target {@link Account} 目标账户
     * @param amount 转账额度
     */
    public void transfer(Account target, int amount) {
        synchronized (Account.class) {
            if (this.money >= amount) {
                this.setMoney(this.getMoney() - amount);
                target.setMoney(target.getMoney() + amount);
            }
        }
    }
}
